package edu.buffalo.cse.cse486_586.simpledht.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.util.Log;
import edu.buffalo.cse.cse486_586.util.AppUtil;

public class ListeningThread implements Runnable {
	// Debug params
	final private String TAG = "ListeningThread";
	// final private Boolean isDebug = true;
	// Network properties
	private NetWorkService ns;

	public ListeningThread(NetWorkService ns) {
		this.ns = ns;
	}

	@Override
	public void run() {
		try {
			ServerSocket ss = new ServerSocket(AppUtil.PORT);
			while (true) {
				Socket s = ss.accept();
				if (s != null) {
					String pkg = read(s);
					Log.d(TAG, "Recieve ===>" + pkg);
					s.close();
					ns.processReceivedContent(pkg);
				}
			}
		} catch (IOException e) {
			Log.e(TAG, "Exception", e);
		}
	}

	public String read(Socket s) throws IOException {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				s.getInputStream()));
		String res = "";
		String inputLine = null;
		while ((inputLine = in.readLine()) != null) {
			res += inputLine;
		}
		in.close();
		return res;
	}

}
